import { defineStore } from 'pinia'
import { login as loginApi } from '@/api/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: JSON.parse(localStorage.getItem('user') || 'null'),
    isLoggedIn: false
  }),

  getters: {
    // 是否已登录
    isAuthenticated: (state) => !!state.token,
    // 是否是管理员
    isAdmin: (state) => state.user?.role === 'ADMIN',
    // 用户信息
    userInfo: (state) => state.user
  },

  actions: {
    // 登录
    async login(loginForm) {
      try {
        const response = await loginApi(loginForm)
        const { token, user } = response
        
        this.token = token
        this.user = user
        this.isLoggedIn = true
        
        // 保存到本地存储
        localStorage.setItem('token', token)
        localStorage.setItem('user', JSON.stringify(user))
        
        return { success: true, data: response }
      } catch (error) {
        return { success: false, error: error.message }
      }
    },

    // 退出登录
    logout() {
      this.token = ''
      this.user = null
      this.isLoggedIn = false
      
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    },

    // 初始化用户状态
    initUserState() {
      const token = localStorage.getItem('token')
      const user = localStorage.getItem('user')
      
      if (token && user) {
        this.token = token
        this.user = JSON.parse(user)
        this.isLoggedIn = true
      }
    }
  }
})
